//引入vue
import Vue from 'vue'
//引入vue-router
import VueRouter from 'vue-router'
import store from '@/store/index'

//使用VueRouter
Vue.use(VueRouter)

//重写push和replace方法
//先备份push和replace的原方法
let originPush = VueRouter.prototype.push;
let originReplace = VueRouter.prototype.replace;

//重写push和replace方法，添加一个成功和失败的回调函数（针对编程式导航）
//第一个参数，告诉原来push方法，你往哪跳转
//第二个参数，成功回调
//第三个参数，失败回调
VueRouter.prototype.push = function (location, resolve, reject) {
    if (resolve && reject) {
        originPush.call(this, location, resolve, reject)
    } else {
        originPush.call(this, location, () => {
        }, () => {
        })
    }
}
VueRouter.prototype.replace = function (location, resolve, reject) {
    if (resolve && reject) {
        originReplace.call(this, location, resolve, reject)
    } else {
        originReplace.call(this, location, () => {
        }, () => {
        })
    }
}

//配置路由组件
// import Home from '@/pages/Home/index'
const foo=()=>{return import('@/pages/Home/index')}
import Login from '@/pages/Login/index'
import Register from '@/pages/Register/index'
// import Search from '@/pages/Search/index'
// import Detail from '@/pages/Detail/index'
import AddCartSuccess from '@/pages/AddCartSuccess/index'
import ShopCart from '@/pages/ShopCart/index'
import Trade from '@/pages/Trade/index'
import Pay from '@/pages/Pay/index'
import PaySuccess from '@/pages/PaySuccess/index'
import Center from '@/pages/Center/index'

//配置二级路由
import MyOrder from '@/pages/Center/myOrder/index'
import GroupOrder from '@/pages/Center/groupOrder/index'

let router = new VueRouter({
    mode:'history',
    routes: [
        {
            name: 'center',
            component: Center,
            path: '/center',
            meta: {//路由元信息
                show: true,
            },
            children:[
                {
                    name:'myorder',
                    component:MyOrder,
                    path:"myorder",
                },
                {
                    name:'grouporder',
                    component:GroupOrder,
                    path:'grouporder',
                },
                {
                    path:'/center',
                    redirect:'/center/myorder'
                }
            ]
        },
        {
            name: 'paysuccess',
            component: PaySuccess,
            path: '/paysuccess',
            beforeEnter:(to, from, next)=>{
                if(from.path=='/pay'){
                    next();
                }else{
                    next(false);
                }
            },
            meta: {//路由元信息
                show: true,
            }
        },
        {
            name: 'pay',
            component: Pay,
            path: '/pay',
            beforeEnter:(to,from,next)=>{
                if(from.path=='/trade'){
                    next();
                }else{
                    next(false);
                }
            },
            meta: {//路由元信息
                show: true,
            }
        },
        {
            name: 'trade',
            component: Trade,
            path: '/trade',
            //添加了组件内守卫
            meta: {//路由元信息
                show: true,
            }
        },
        {
            name: 'shopcart',
            component: ShopCart,
            path: '/shopcart',
            meta: {//路由元信息
                show: true,
            }
        },
        {
            name: 'addcartsuccess',
            component: AddCartSuccess,
            path: '/addcartsuccess',
            meta: {//路由元信息
                show: true,
            }
        },
        {
            component: ()=>import('@/pages/Detail/index'),
            path: '/detail/:skuId',
            meta: {//路由元信息
                show: true,
            }
        },
        {
            //当打包构建项目时，JavaScript包会变得非常大，影响加载效率
            //如果我们把不同路由对应的组件拆分成不同的块，当调用时才加载组件，就可以实现更加高效
            //路由懒加载，实现路由的高效性，只有触发路由时才导入路由组件
            component: foo,
            path: '/home',
            meta: {//路由元信息
                show: true,
            }
        },
        {
            path: '/login',
            component: Login,
            meta: {
                show: false,
            }
        },
        {
            path: '/register',
            component: Register,
            meta: {
                show: false,
            }
        },
        {
            name: 'search',
            path: '/search/:keyword?',//: 为占位符，?代表params参数可传可不传
            component: ()=>{return import('@/pages/Search/index')},
            meta: {
                show: true,
            }
        },
        //设置重定向，当项目跑起来时自动定向访问home页面，
        {
            path: '*',
            redirect: '/home'
        }
    ],
    //页面滚动行为
    scrollBehavior(to, from, savedPosition) {
        // return desired position
        return {
            y: 0//y轴
        }
    }
})

//编辑前置守卫逻辑
router.beforeEach(async (to, from, next) => {
    let token = store.state.user.token;
    let name = store.state.user.userInfo.name;
    if (token) {
        //登录成功
        if (to.path == '/login' || to.path == '/register') {
            //控制去登录的路径跳转到首页
            next('/');
        } else {
            if (name) {
                //用户名存在，通行
                next();
            } else {
                //当登录成功后，用户名获取不到，为空，则需要重新获取userInfo
                try {
                    //重新获取userInfo
                    await store.dispatch('getUserInfoByToken')
                    next();
                } catch (error) {
                    //如果userInfo获取失败,则表明token失效，获取不到userInfo
                    //token失效，重新登录
                    await store.dispatch('logout')
                    next('/login')
                }
            }
        }
    }else {
        //未登录 当用户未登录时，订单详情页、个人主页、支付详情页、交易详情页均不能跳转
        let toPath=to.path;
        if(toPath.indexOf('/trade')!=-1||toPath.indexOf('/pay')!=-1||toPath.indexOf('/center')!=-1){
            //均重新跳转到login页
            next('/login?redirect='+toPath);
        }else {
            //不是去以上页面，放行
            next();
        }
    }
})
export default router;